package com.example.video.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.example.video.entity.Account;
import com.example.video.entity.Device;
import com.example.video.entity.OuterAccount;
import com.example.video.entity.Video;
import com.example.video.service.IAccountService;
import com.example.video.common.Result;
import com.example.video.mapper.AccountMapper;
import com.example.video.mapper.VideoMapper;
import com.example.video.util.RoleUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author qiusuyang
 * @since 2024-04-13
 */
@Slf4j
@Service
public class AccountServiceImpl implements IAccountService {

    @Resource
    private AccountMapper mapper;
    @Resource
    private VideoMapper videoMapper;

    @Resource
    private PlatformServiceImpl platformService;

    /**
     * @desc 根据页数和大小来查询源账户列表
     * @param page 页数，从1开始
     * @param size 每页大小
     * @return 获取的源账号列表
     */
    @Deprecated
    @Override
    public List<Account> getList(Integer page, Integer size){
        QueryWrapper<Account> qwrapper = new QueryWrapper<>();
        qwrapper.orderByDesc("id");
        IPage<Account> iPage = mapper.selectPage(new Page<>(page,size),qwrapper);
        return iPage.getRecords();
    }

    @Override
    public List<Account> search(Integer page, Integer size, String name, Integer platformId){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        log.info("name = "+name +" platformId = "+platformId+" platform name = ");
        // 获取用户的所有权限
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        // 提取并格式化角色
        List<String> formattedRoles = RoleUtils.extractAndFormatRoles(authorities);

        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        log.info("AccountSrvImp -> search ->msg: formateRoles"+formattedRoles);
        // 如果formattedRoles中包含[[ROLE_ADMIN]]，则返回表中所有数据
        if (formattedRoles.size() == 1 && formattedRoles.get(0).equals("[ROLE_ADMIN]")) {

        } else {
            // 设置查询条件，匹配formattedRoles列表中的任一角色
            if (!formattedRoles.isEmpty()) {
                queryWrapper.in("role", formattedRoles);
            }
        }

        if(platformId == 0){
            queryWrapper.like("name",name)
                        .orderByDesc("id")
            ;
            // 如果formattedRoles中包含[[ROLE_ADMIN]]，则返回表中所有数据
            if (formattedRoles.size() == 1 && formattedRoles.get(0).equals("[ROLE_ADMIN]")) {
                IPage<Account> iPage = mapper.selectPage(new Page<>(page,size), queryWrapper);
             return iPage.getRecords();
            } else {
                // 设置查询条件，匹配formattedRoles列表中的任一角色
                if (!formattedRoles.isEmpty()) {
                    queryWrapper.in("role", formattedRoles);
                }
                IPage<Account> iPage = mapper.selectPage(new Page<>(page,size), queryWrapper);
                return iPage.getRecords();
            }


        }else{
            queryWrapper.like("name",name)
                        .eq("platform",platformService.getItem(platformId).getPlatformName())
                        .orderByDesc("id")
                    ;

            if (formattedRoles.size() == 1 && formattedRoles.get(0).equals("[ROLE_ADMIN]")) {
                // 不设置任何角色条件，返回所有用户数据
                IPage<Account> ipage = mapper.selectPage(new Page<>(page,size), queryWrapper);
                return ipage.getRecords();
            } else {
                // 设置查询条件，匹配formattedRoles列表中的任一角色
                if (!formattedRoles.isEmpty()) {
                    queryWrapper.in("role", formattedRoles);
                }
                IPage<Account> ipage = mapper.selectPage(new Page<>(page,size), queryWrapper);
                return ipage.getRecords();
            }

        }
    }

    @Override
    public List<Account> searchByName(String name){
        return mapper.selectList(new QueryWrapper<Account>().like("name",name).orderByDesc("id"));
    }


    /**
     * @desc 根据id查询源账号
     * @param id 查询的源账号id
     * @return 查询到的源账号
     */
    @Override
    public Account getItem(Integer id){
        return mapper.selectById(id);
    }

    /**
     * @desc 保存源账号修改或者新增
     * @param account 要修改或保存的源账号
     * @return 是否操作成功
     */
    @Override
    public int save(Account account){
        int k,rs;
        if(account.getId() > 0){
            k = mapper.updateById(account);
        }else{
            k = mapper.insert(account);
        }
        rs = account.getId();
        return rs;
    }

    /**
     * @desc 根据id删除
     * @param id 要删除的源账号id
     * @return 是否操作成功
     */
    @Override
    public boolean delete(Integer id){


        return mapper.deleteById(id) > 0 && videoMapper.delete(new QueryWrapper<Video>().eq("account_id",id)) > 0;
    }


    @Override
    public void updateByUrl(Account account) {
        QueryWrapper<Account> wrapper = new QueryWrapper<>();
        wrapper.eq("url",account.getUrl());
        Account account_temp = mapper.selectOne(wrapper);
        account_temp.setAvatarUrl(account.getAvatarUrl());
        account_temp.setName(account.getName());
        mapper.updateById(account_temp);
    }

    @Override
    public long getCountByName(String name) {
        return mapper.selectCount(new QueryWrapper<Account>().like("name",name));
    }

    @Override
    public long getCount(){
        return mapper.selectCount(new QueryWrapper<Account>());
    }

    @Override
    public void updateById(Account account) {
        mapper.updateById(account);
    }


    @Override
    public List<Account> searchByNameAndplatformId(String name, Integer platformId) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        // 获取用户的所有权限
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        // 提取并格式化角色
        List<String> formattedRoles = RoleUtils.extractAndFormatRoles(authorities);

        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        log.info("AccountSrvImp -> search ->msg: formateRoles"+formattedRoles);
        // 如果formattedRoles中包含[[ROLE_ADMIN]]，则返回表中所有数据
        if (formattedRoles.size() == 1 && formattedRoles.get(0).equals("[ROLE_ADMIN]")) {

        } else {
            // 设置查询条件，匹配formattedRoles列表中的任一角色
            if (!formattedRoles.isEmpty()) {
                queryWrapper.in("role", formattedRoles);
            }
        }

        if(platformId == 0){
            queryWrapper.like("name",name)
                    .orderByDesc("id")
            ;
            // 如果formattedRoles中包含[[ROLE_ADMIN]]，则返回表中所有数据
            if (formattedRoles.size() == 1 && formattedRoles.get(0).equals("[ROLE_ADMIN]")) {

                return mapper.selectList(queryWrapper);
            } else {
                // 设置查询条件，匹配formattedRoles列表中的任一角色
                if (!formattedRoles.isEmpty()) {
                    queryWrapper.in("role", formattedRoles);
                }

                return mapper.selectList(queryWrapper);
            }


        }else{
            queryWrapper.like("name",name)
                    .eq("platform",platformService.getItem(platformId).getPlatformName())
                    .orderByDesc("id")
            ;

            if (formattedRoles.size() == 1 && formattedRoles.get(0).equals("[ROLE_ADMIN]")) {
                // 不设置任何角色条件，返回所有用户数据
                return mapper.selectList(queryWrapper);
            } else {
                // 设置查询条件，匹配formattedRoles列表中的任一角色
                if (!formattedRoles.isEmpty()) {
                    queryWrapper.in("role", formattedRoles);
                }
                return mapper.selectList(queryWrapper);
            }

        }
    }

    @Override
    //查询是否含有还未绑定设备ID的Account并绑定
    public Result<List<OuterAccount>> bind(String deviceId) {
        Result<List<OuterAccount>> rs = new Result<>();
        //先检查该设备ID是否已绑定账户
        QueryWrapper<Account> checkIsBinded = new QueryWrapper<Account>()
                .eq("device_id",deviceId);
        List<Account> checkAccounts = mapper.selectList(checkIsBinded);
//        log.info("AccountImpl -> bind -> msg: checkaccount = "+checkAccounts);
        if (checkAccounts.size()!=0){
            Account account = Db.lambdaQuery(Account.class)
                    .eq(Account::getDeviceId,deviceId)
                    .one();

            rs.setCode(0);
            rs.setMsg("该id已绑定过账号");
            List<OuterAccount> outerAccounts = Db.lambdaQuery(OuterAccount.class)
                    .eq(OuterAccount::getAccountId, account.getId())
                    .select(OuterAccount::getUserAccount,
                            OuterAccount::getUserPwd,
                            OuterAccount::getPlatformName,
                            OuterAccount::getLanguage
                    )
                    .list();
            rs.setCount(outerAccounts.size());
            rs.setData(outerAccounts );
            return rs;
        }
        //先获取所有未绑定设备ID的数据
        QueryWrapper<Account> queryWrapper = new QueryWrapper<Account>()
                .isNull("device_id")
                .orderByAsc("id");
        List<Account> accounts = mapper.selectList(queryWrapper);
//        log.info("AccountImpl -> bind -> msg: account = "+accounts);
        if(accounts == null){
            rs.setMsg("绑定失败：所有账户都已绑定设备");
            rs.setData(null);
            rs.setCode(-1);
            return rs;
        }
        //如果还有未绑定ID的Account，就给未绑定ID数组的第一个元素绑定ID
        Account account = accounts.get(0);
        account.setDeviceId(deviceId);
        //更新Account数据库表
        mapper.updateById(account);
        //更新Device数据库表
        Device device = new Device();
        device.setDeviceId(deviceId);
        Db.save(device);
        //查询这个账户所对应的外部账户并返回
        rs.setCode(0);
        rs.setMsg("成功");
        List<OuterAccount> outerAccounts = Db.lambdaQuery(OuterAccount.class)
                .eq(OuterAccount::getAccountId, account.getId())
                .list();
        rs.setCount(outerAccounts.size());
        rs.setData(outerAccounts );
        return rs;
    }

    @Override
    public Account selectOne(String deviceId) {
        QueryWrapper<Account> wrapper = new QueryWrapper<>();
        wrapper.eq("device_id",deviceId);
        return mapper.selectOne(wrapper);
    }


    @Override
    public Account getItemByUrl(String url) {
        return mapper.selectOne(new QueryWrapper<Account>().select("name","url").eq("url",url));
    }

    @Override
    public List<Account> getListByAccountIdArr(List<Integer> idList) {
        return mapper.selectList(new QueryWrapper<Account>().in("id",idList));
    }

    @Override
    public Account getItemByDeviceId(String deviceId) {
        return mapper.selectOne(new QueryWrapper<Account>().eq("device_id",deviceId));
    }
}
